<template>
  <div class="app-container">
    <!-- 使用封装的加载遮罩组件 -->
    <loading-overlay :visible="uploadLoading" text="正在处理数据，请稍候..." />
    <!-- 过滤栏 -->
    <filter-container 
      ref="filterContainer"
      :total="total" 
      search-placeholder="请输入转运单号" 
      @search="handleFilter"
    >
      <template #filter-items>
      </template>
      <template #action-buttons>
        <el-button
          v-if="multipleSelection.length > 0"
          class="filter-item"
          type="danger"
          icon="el-icon-delete"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
        <el-button
          v-if="multipleSelection.length > 0"
          class="filter-item"
          type="warning"
          icon="el-icon-date"
          @click="handleBatchUpdateDate"
        >
          批量修改日期
        </el-button>
        <el-button
          class="filter-item"
          type="success"
          icon="el-icon-edit"
          @click="handleTransferInput"
        >
          转运录入
        </el-button>
        <el-button
          class="filter-item"
          type="info"
          icon="el-icon-document"
          @click="handleViewSavedPDFs"
        >
          查看保存的PDF
        </el-button>
        <el-upload
          ref="upload"
          class="filter-item upload-button"
          :action="uploadUrl"
          :headers="uploadHeaders"
          :show-file-list="false"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :before-upload="beforeUpload"
        >
          <el-button class="filter-item" type="success" icon="el-icon-plus" style="height: 40px;">
            新增转运单
          </el-button>
        </el-upload>
        <el-button
          v-if="multipleSelection.length > 0"
          class="filter-item"
          type="primary"
          icon="el-icon-download"
          @click="handleExport"
        >
          导出Excel
        </el-button>
      </template>
      <template #selection-info>
        <span v-if="multipleSelection.length > 0" class="selection-info">
          已选择 <span class="selection-count">{{ multipleSelection.length }}</span> 条数据
        </span>
      </template>
    </filter-container>
    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @selection-change="handleSelectionChange"
      class="custom-table"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column label="订单号" prop="cw_no" align="center" min-width="160">
        <template slot-scope="{row}">
          <div class="order-no-container">
            <el-tooltip v-if="row.remark" effect="dark" placement="top">
              <div slot="content">
                <p style="margin: 0; white-space: pre-wrap;">{{ row.remark }}</p>
              </div>
              <i class="el-icon-warning remark-icon"></i>
            </el-tooltip>
            <span class="copy-text" @click="handleCopy(row.cw_no)">{{ row.cw_no }}</span>
          </div>
          <div class="tags-container">
            <el-tooltip v-if="row.is_pickup" effect="dark" placement="top">
              <div slot="content">
                <p style="margin: 0;">自提时间：{{ row.pickup_time ? row.pickup_time.replace('T', ' ').replace('+09:00', '') : '无自提时间' }}</p>
              </div>
              <el-tag size="mini" class="pickup-tag">自提</el-tag>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="物流员" prop="created_by_username" align="center" min-width="100">
        <template slot-scope="{row}">
          <span>{{ row.created_by_username || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发货方式" align="center" min-width="90">
        <template slot-scope="{row}">
          <span :class="['shipping-method', row.shipping_method === 'YAMATO' ? 'yamato' : row.shipping_method === 'SAGAWA' ? 'sagawa' : '']">
            {{ row.shipping_method === 'YAMATO' ? '黑猫' : row.shipping_method === 'SAGAWA' ? '佐川' : row.shipping_method || '-' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="佐川金额" align="center" min-width="90">
        <template slot-scope="{row}">
          <span>{{ row.sagawa_price || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="黑猫金额" align="center" min-width="90">
        <template slot-scope="{row}">
          <span>{{ row.yamato_price || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="都道府県" align="center" min-width="120">
        <template slot-scope="{row}">
          <span class="copy-text" @click="handleCopy(row.state || '-')">
            {{ row.state || '-' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="邮编" prop="postal_code" align="center" min-width="100">
        <template slot-scope="{row}">
          <span>{{ row.postal_code || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="删除状态" prop="is_delete" align="center" min-width="90">
        <template slot-scope="{row}">
          <el-tag :type="row.is_delete ? 'danger' : 'success'">
            {{ row.is_delete ? '已删除' : '未删除' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="create_time" align="center" min-width="160">
        <template slot-scope="{row}">
          <span>{{ row.create_time }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" align="center" min-width="150">
        <template slot-scope="{row}">
          <span>{{ row.remark || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="箱数" prop="box_count" align="center" min-width="80">
        <template slot-scope="{row}">
          <span>{{ row.box_count || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="体积" align="center" min-width="100">
        <template slot-scope="{row}">
          <span>{{ calculateVolume(row) || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="140" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row}">
          <div class="action-buttons">
            <el-button type="primary" size="mini" @click="temp = Object.assign({}, row); dialogFormVisible = true; $nextTick(() => $refs['dataForm'].clearValidate())">
              编辑
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.page_size"
      :page-sizes="[100, 500, 1000, 1500, 2000]"
      :layout="'total, sizes, prev, pager, next, jumper'"
      @pagination="handlePaginationChange"
    />
    <!-- 添加转运数据输入对话框 -->
    <el-dialog title="转运数据录入" :visible.sync="transferInputVisible" width="60%">
      <el-form ref="transferForm" :model="transferData" :rules="transferRules">
        <el-form-item label="承运商" prop="carrier" label-width="100px">
          <el-select v-model="transferData.carrier" placeholder="请选择物流公司" style="width: 100%">
            <el-option label="DHL" value="DHL" />
            <el-option label="UPS" value="UPS" />
            <el-option label="Fedex" value="Fedex" />
          </el-select>
        </el-form-item>
        <el-form-item label="转运数据" prop="data" label-width="100px">
          <el-input
            v-model="transferData.data"
            type="textarea"
            :rows="15"
            placeholder="请输入转运数据，每行一条数据，格式：
ZYZP号
箱数
CW号"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="transferInputVisible = false">取消</el-button>
        <el-button type="primary" @click="handleTransferDataSubmit">确认</el-button>
      </div>
    </el-dialog>
    
    <!-- 查看保存的PDF对话框 -->
    <el-dialog title="保存的PDF文件" :visible.sync="savedPDFsVisible" width="80%" top="5vh">
      <div class="saved-pdfs-container">
        <!-- 筛选条件 -->
        <div class="filter-section" style="margin-bottom: 20px;">
          <el-form :inline="true" :model="pdfFilterForm" class="demo-form-inline">
            <el-form-item label="筛选方式">
              <el-radio-group v-model="pdfFilterForm.filterType" @change="handleFilterTypeChange">
                <el-radio label="days">按天数</el-radio>
                <el-radio label="dateRange">按日期范围</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item v-if="pdfFilterForm.filterType === 'days'" label="查看天数">
              <el-select v-model="pdfFilterForm.days" placeholder="选择天数" @change="loadSavedPDFs">
                <el-option label="最近3天" :value="3" />
                <el-option label="最近7天" :value="7" />
                <el-option label="最近15天" :value="15" />
                <el-option label="最近30天" :value="30" />
              </el-select>
            </el-form-item>
            
            <el-form-item v-if="pdfFilterForm.filterType === 'dateRange'" label="日期范围">
              <el-date-picker
                v-model="pdfFilterForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                @change="loadSavedPDFs"
                style="width: 240px;"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="loadSavedPDFs">刷新</el-button>
            </el-form-item>
          </el-form>
        </div>
        
        <!-- 批量操作按钮 -->
        <div class="batch-actions" style="margin-bottom: 20px;" v-if="selectedPDFs.length > 0">
          <el-button type="success" @click="batchDownloadSelectedPDFs">
            批量下载 ({{ selectedPDFs.length }})
          </el-button>
          <el-button type="danger" @click="batchDeleteSelectedPDFs">
            批量删除 ({{ selectedPDFs.length }})
          </el-button>
        </div>
        
        <!-- PDF列表 -->
        <el-table 
          :data="savedPDFs" 
          v-loading="pdfsLoading" 
          style="width: 100%"
          @selection-change="handlePDFSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="filename" label="文件名" width="300" />
          <el-table-column prop="date" label="日期" width="120" />
          <el-table-column prop="username" label="用户" width="120" />
          <el-table-column prop="carrier" label="承运商" width="120" />
          <el-table-column prop="size" label="文件大小" width="120">
            <template slot-scope="scope">
              {{ formatFileSize(scope.row.size) }}
            </template>
          </el-table-column>
          <el-table-column prop="created_time" label="创建时间" width="180" />
          <el-table-column label="操作" width="250">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="previewPDF(scope.row)">预览</el-button>
              <el-button size="mini" type="success" @click="downloadPDF(scope.row)">下载</el-button>
              <el-button size="mini" type="danger" @click="deletePDF(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
    
    <!-- PDF预览对话框 -->
    <el-dialog title="PDF预览" :visible.sync="pdfPreviewVisible" width="90%" top="5vh">
      <div class="pdf-preview-container">
        <div v-if="currentPreviewPDF" class="pdf-preview-wrapper">
          <div class="pdf-info" style="margin-bottom: 10px; padding: 10px; background: #f5f7fa; border-radius: 4px;">
            <strong>文件名：</strong>{{ currentPreviewPDF.filename }}<br>
            <strong>创建时间：</strong>{{ currentPreviewPDF.created_time }}<br>
            <strong>文件大小：</strong>{{ formatFileSize(currentPreviewPDF.size) }}
          </div>
          <iframe 
            :src="getPDFPreviewUrl(currentPreviewPDF)" 
            width="100%" 
            height="600px" 
            frameborder="0"
            style="border: 1px solid #ddd; border-radius: 4px;"
            @load="onIframeLoad"
            @error="onIframeError"
          />
          <div v-if="iframeError" class="iframe-error" style="text-align: center; padding: 20px; color: #f56c6c; background: #fef0f0; border: 1px solid #fbc4c4; border-radius: 4px; margin-top: 10px;">
            <i class="el-icon-warning"></i>
            <p>PDF预览加载失败，请尝试在新标签页中打开或直接下载文件</p>
            <el-button type="primary" size="small" @click="openPDFInNewTab">在新标签页中打开</el-button>
            <el-button type="success" size="small" @click="downloadCurrentPDF">下载文件</el-button>
          </div>
          <div v-if="!currentPreviewPDF" class="no-pdf-message" style="text-align: center; padding: 50px; color: #999;">
            请选择要预览的PDF文件
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="pdfPreviewVisible = false">关闭</el-button>
        <el-button type="primary" @click="downloadCurrentPDF">下载</el-button>
        <el-button type="success" @click="openPDFInNewTab">在新标签页中打开</el-button>
      </div>
    </el-dialog>
    
    <!-- 编辑转运单对话框 -->
    <el-dialog title="编辑转运单" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="100px"
      >
      <el-divider content-position="left">自提信息</el-divider>
        <el-form-item label="是否自提" prop="is_pickup">
          <el-switch
            v-model="temp.is_pickup"
            active-text="自提"
            inactive-text="非自提"
            active-color="#67C23A"
            @change="handlePickupChange"
          />
        </el-form-item>
        <el-form-item label="自提时间" prop="pickup_time">
          <el-date-picker
            v-model="temp.pickup_time"
            type="datetime"
            placeholder="选择自提时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;"
            :disabled="!temp.is_pickup"
          />
        </el-form-item>
        <el-divider content-position="left">发货信息</el-divider>
        <div class="volume-info" style="margin-bottom: 20px;">
          <span>体积：{{ calculateVolume(temp) || '-' }} cm³</span>
        </div>
        <el-form-item label="订单号" prop="cw_no">
          <el-input v-model="temp.cw_no" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="发货方式" prop="shipping_method">
          <el-select v-model="temp.shipping_method" placeholder="请选择">
            <el-option label="佐川" value="SAGAWA" />
            <el-option label="黑猫" value="YAMATO" />
          </el-select>
        </el-form-item>
        <el-form-item label="都道府県" prop="state">
          <el-input v-model="temp.state" />
        </el-form-item>
        <el-form-item label="邮编" prop="postal_code">
          <el-input v-model="temp.postal_code" />
        </el-form-item>
        <el-form-item label="地址1">
          <el-input :value="temp.address1" readonly disabled />
        </el-form-item>
        <el-form-item label="地址2">
          <el-input :value="temp.address2" readonly disabled />
        </el-form-item>
        <el-form-item label="城市">
          <el-input :value="temp.city" readonly disabled />
        </el-form-item>
        <el-form-item label="电话">
          <el-input :value="temp.phone_number" readonly disabled />
        </el-form-item>
        <el-form-item label="收货人">
          <el-input :value="temp.attention" readonly disabled />
        </el-form-item>
        <el-form-item label="公司">
          <el-input :value="temp.company_name" readonly disabled />
        </el-form-item>
        <el-divider content-position="left">其他信息</el-divider>
        <el-form-item label="创建日期" prop="create_time">
          <el-date-picker
            v-model="temp.create_time"
            type="datetime"
            placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="箱数" prop="box_count">
          <el-input v-model="temp.box_count" placeholder="请输入箱数" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="temp.remark" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="备注完成状态">
          <el-switch
            v-model="temp.remark_status"
            :active-value="true"
            :inactive-value="false"
            active-text="备注完成"
            inactive-text="未完成"
            active-color="#67C23A"
            inactive-color="#E6A23C"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateData()">确认</el-button>
      </div>
    </el-dialog>
    <!-- 批量修改日期对话框 -->
    <el-dialog title="批量修改创建日期" :visible.sync="batchDateDialogVisible" width="600px">
      <el-form ref="batchDateForm" :model="batchDateForm" :rules="batchDateRules" label-width="120px">
        <el-form-item label="选择日期时间" prop="createTime">
          <el-date-picker
            v-model="batchDateForm.createTime"
            type="datetime"
            placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item>
          <p style="color: #909399; font-size: 14px; margin: 0;">
            将批量修改 <strong style="color: #F56C6C;">{{ multipleSelection.length }}</strong> 条记录的创建日期
          </p>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="batchDateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmBatchUpdateDate" :loading="batchDateLoading">确认修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchTransferList, createTransferOrder, updateTransferOrder, deleteTransferOrder, generateTransferPDF, saveTransferPDF, getSavedPDFs, deletePDF, batchDeletePDFs, batchDownloadPDFs, searchPostalCode, getShippingMethod, batchDeleteTransferlOrders, exportTransferOrders, batchUpdateTransferOrdersDate } from '@/api/shipping'
import Pagination from '@/components/Pagination'
import FilterContainer from './components/FilterContainer.vue'
import LoadingOverlay from './components/LoadingOverlay.vue'

export default {
  name: 'TransferOrder',
  components: { 
    Pagination,
    FilterContainer,
    LoadingOverlay
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      postalCodeResults: {},
      listQuery: {
        page: 1,
        page_size: 100, 
        keyword: undefined,
        is_delete: false,
        deleteStatus: undefined
      },
      uploadUrl: process.env.VUE_APP_BASE_API.replace(/['"]/g, '') + '/v1/shipping/transfer/import',
      uploadHeaders: {
        Authorization: 'Bearer ' + this.$store.getters.token
      },
      statusOptions: [
        { label: '已删除', value: true },
        { label: '未删除', value: false }
      ],
      temp: {
        id: undefined,
        cw_no: '',
        shipping_method: '',
        state: '',
        postal_code: '',
        box_count: '',
        address1: '',
        address2: '',
        city: '',
        phone_number: '',
        attention: '',
        company_name: '',
        create_time: '',
        is_pickup: false,
        pickup_time: '',
        remark: '',
        remark_status: false
      },
      dialogFormVisible: false,
      rules: {
        cw_no: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
        state: [{ required: true, message: '请输入都道府県', trigger: 'blur' }],
        postal_code: [{ required: true, message: '请输入邮编', trigger: 'blur' }],
        box_count: [{ required: true, message: '请输入箱数', trigger: 'blur' }],
        pickup_time: [
          {
            validator: (rule, value, callback) => {
              if (this.temp.is_pickup && !value) {
                callback(new Error('自提时间不能为空'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ]
      },
      multipleSelection: [],
      transferInputVisible: false,
      transferData: {
        carrier: '',
        data: ''
      },
      transferRules: {
        carrier: [{ required: true, message: '请选择物流公司', trigger: 'change' }],
        data: [{ required: true, message: '请输入转运数据', trigger: 'blur' }]
      },
      uploadLoading: false,
      batchDateDialogVisible: false,
      batchDateLoading: false,
      batchDateForm: {
        createTime: ''
      },
      batchDateRules: {
        createTime: [{ required: true, message: '请选择创建日期', trigger: 'change' }]
      },
      savedPDFsVisible: false,
      savedPDFs: [],
      pdfsLoading: false,
      selectedPDFs: [],
      pdfFilterForm: {
        filterType: 'days',
        days: 7,
        dateRange: []
      },
      pdfPreviewVisible: false,
      currentPreviewPDF: null,
      iframeError: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handlePickupChange(value) {
      // 当自提状态改变时，清空自提时间并重新验证
      if (!value) {
        this.temp.pickup_time = ''
      }
      // 触发表单验证
      this.$nextTick(() => {
        this.$refs.dataForm.validateField('pickup_time')
      })
    },
    async getList() {
      this.listLoading = true
      try {
        const response = await fetchTransferList(this.listQuery)
        
        let items = []
        let total = 0
        
        if (response.results && response.results.data && response.results.data.items) {
          items = response.results.data.items
          total = response.count || 0
        }
        
        this.list = items
        this.total = total
        this.listLoading = false
        
        // 等待邮编信息查询完成
        await this.queryPostalCodes()
      } catch (error) {
        console.error('获取数据失败:', error)
        this.list = []
        this.total = 0
        this.listLoading = false
      }
    },
    handleFilter(params) {
      this.listQuery.page = 1
      
      // 处理日期范围
      if (params.dateRange && params.dateRange.length === 2) {
        this.listQuery.start_date = params.dateRange[0]
        this.listQuery.end_date = params.dateRange[1]
      } else {
        delete this.listQuery.start_date
        delete this.listQuery.end_date
      }
      
      // 更新查询参数
      this.listQuery = {
        ...this.listQuery,
        keyword: params.keyword,
        is_delete: params.is_delete
      }

      // 如果is_delete为null或undefined，则删除该参数，显示所有数据
      if (params.is_delete === null || params.is_delete === undefined) {
        delete this.listQuery.is_delete
      }

      console.log('查询参数:', this.listQuery)
      this.getList()
    },
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                     file.type === 'application/vnd.ms-excel'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isExcel) {
        this.$message.error('只能上传Excel文件!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('文件大小不能超过 2MB!')
        return false
      }
      return true
    },
    async handleUploadSuccess(response) {
      // 显示加载遮罩
      this.uploadLoading = true
      
      // 检查响应是否成功
      if (response.code === 200 && response.data) {
        const { success_count, error_count, skipped_count, error_records } = response.data
        
        // 构建基础成功消息
        let message = ''
        let type = 'success'
        
        if (success_count > 0) {
          message = `成功导入 ${success_count} 条记录`
          
          // 添加其他统计信息
          if (skipped_count > 0) {
            message += `，跳过 ${skipped_count} 条不合法数据`
          }
          if (error_count > 0) {
            message += `，${error_count} 条记录导入失败`
          }
        } else {
          message = `导入失败：没有成功导入的记录`
          type = 'warning'
          
          if (skipped_count > 0) {
            message += `，跳过 ${skipped_count} 条不合法数据`
          }
        }
        
        // 如果有错误记录，显示详细错误信息
        if (error_count > 0 && error_records && error_records.length > 0) {
          // 统计错误类型
          const errorStats = {}
          error_records.forEach(record => {
            const errorType = record.error
            if (!errorStats[errorType]) {
              errorStats[errorType] = []
            }
            // 支持多种编号字段格式
            const recordNo =  record.fs_no || record.cw_no || record.order_no || '未知编号'
            errorStats[errorType].push(recordNo)
          })
          
          // 构建详细错误消息
          let detailMessage = message + '\n\n详细失败信息：\n'
          Object.keys(errorStats).forEach(errorType => {
            const orderNumbers = errorStats[errorType]
            detailMessage += `\n• ${errorType}：${orderNumbers.length}条`
            
            // 如果同类型错误较少，显示具体的编号
            if (orderNumbers.length <= 10) {
              detailMessage += `\n  ${orderNumbers.join(', ')}`
            } else {
              // 如果错误较多，只显示前几个
              detailMessage += `\n  ${orderNumbers.slice(0, 10).join(', ')} 等${orderNumbers.length}条`
            }
          })
          
          // 使用MessageBox显示详细信息
          this.$alert(detailMessage, '导入结果详情', {
            confirmButtonText: '确定',
            type: type,
            customClass: 'upload-result-dialog'
          })
        } else {
          // 没有错误记录，使用简单通知
          this.$notify({
            title: '导入完成',
            message: message,
            type: type,
            duration: 4000
          })
        }

        // 如果有成功导入的记录，等待数据处理完成后刷新页面
        if (success_count > 0) {
          try {
            await this.getList()
            // 等待一下确保所有异步操作完成
            setTimeout(() => {
              this.uploadLoading = false // 隐藏加载遮罩
              location.reload()
            }, 1000)
          } catch (error) {
            console.error('获取数据失败:', error)
            // 即使失败也刷新页面
            setTimeout(() => {
              this.uploadLoading = false // 隐藏加载遮罩
              location.reload()
            }, 1000)
          }
        } else {
          // 没有成功记录，直接隐藏加载遮罩
          this.uploadLoading = false
        }
      } else {
        // 隐藏加载遮罩
        this.uploadLoading = false
        this.$notify({
          title: '导入失败',
          message: response.message || '导入失败，请重试',
          type: 'error',
          duration: 3000
        })
      }
    },
    handleUploadError(err) {
      // 隐藏加载遮罩
      this.uploadLoading = false
      console.error('Upload error:', err)
      this.$notify({
        title: '导入失败',
        message: '导入失败',
        type: 'error',
        duration: 3000
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        cw_no: '',
        shipping_method: '',
        state: '',
        postal_code: '',
        box_count: '',
        address1: '',
        address2: '',
        city: '',
        phone_number: '',
        attention: '',
        company_name: '',
        create_time: '',
        is_pickup: false,
        pickup_time: '',
        remark: '',
        remark_status: false
      }
    },
    async updateData() {
      try {
        const valid = await this.$refs['dataForm'].validate()
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          await updateTransferOrder(tempData)
          const index = this.list.findIndex(v => v.id === this.temp.id)
          this.list.splice(index, 1, this.temp)
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000
          })
        }
      } catch (error) {
        console.error('更新失败:', error)
        
        // 解析错误信息
        let errorMessage = '更新失败'
        if (error.response && error.response.data) {
          const errorData = error.response.data
          if (errorData.error) {
            // 如果有具体的字段错误，显示第一个字段的错误信息
            const firstError = Object.values(errorData.error)[0]
            if (Array.isArray(firstError) && firstError.length > 0) {
              errorMessage = firstError[0]
            } else if (typeof firstError === 'string') {
              errorMessage = firstError
            }
          } else if (errorData.message) {
            errorMessage = errorData.message
          }
        }
        
        this.$notify({
          title: '错误',
          message: errorMessage,
          type: 'error',
          duration: 3000
        })
      }
    },
    async handleDelete(row) {
      try {
        await this.$confirm('警告：删除后数据将永久丢失，无法恢复！', '删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
        
        await deleteTransferOrder(row.id)
        const index = this.list.findIndex(v => v.id === row.id)
        this.list.splice(index, 1)
        this.total = this.total - 1
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          this.$notify({
            title: '错误',
            message: '删除失败',
            type: 'error',
            duration: 2000
          })
        }
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    async handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要删除的订单')
        return
      }
      
      try {
        await this.$confirm(`删除后该记录将不再显示在列表中。`, '批量删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const cwNos = this.multipleSelection.map(item => item.cw_no)
        await batchDeleteTransferlOrders(cwNos)
        this.$notify({
          title: '成功',
          message: '批量删除成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error)
          this.$notify({
            title: '错误',
            message: '批量删除失败',
            type: 'error',
            duration: 2000
          })
        }
      }
    },
    handleCopy(text) {
      const textarea = document.createElement('textarea')
      textarea.value = text
      document.body.appendChild(textarea)
      textarea.select()
      document.execCommand('copy')
      document.body.removeChild(textarea)
      this.$notify({
        title: '成功',
        message: '复制成功',
        type: 'success',
        duration: 2000
      })
    },
    handleTransferInput() {
      this.transferInputVisible = true
      this.transferData.carrier = ''
      this.transferData.data = ''
    },
    async handleTransferDataSubmit() {
      try {
        const valid = await this.$refs.transferForm.validate()
        if (!valid) {
          return
        }

        if (!this.transferData.data.trim()) {
          this.$message.warning('请输入转运数据')
          return
        }

        // 解析数据
        const lines = this.transferData.data.trim().split('\n')
        const transferOrders = []
        let currentOrder = null
        let boxCount = null

        // 遍历所有行
        for (let i = 0; i < lines.length; i++) {
          const line = lines[i].trim()

          // 检查是否以ZYJP开头
          if (line.startsWith('ZYJP')) {
            // 如果已经有当前订单，先保存它
            if (currentOrder) {
              transferOrders.push(currentOrder)
            }
            // 创建新订单
            currentOrder = {
              zyzpNo: line,
              boxCount: '001',
              cwNo: []
            }
            boxCount = null
          }
          // 检查是否是箱数
          else if (currentOrder && !boxCount && /^\d+$/.test(line)) {
            boxCount = line.padStart(3, '0')
            currentOrder.boxCount = boxCount
          }
          // 检查是否以CW或HF开头
          else if (currentOrder && (line.startsWith('CW') || line.startsWith('HF'))) {
            currentOrder.cwNo.push(line)
          }
        }

        // 添加最后一个订单
        if (currentOrder) {
          transferOrders.push(currentOrder)
        }

        if (transferOrders.length === 0) {
          this.$message.warning('没有有效的转运数据')
          return
        }

        // 显示加载中
        this.$loading({
          lock: true,
          text: '正在生成PDF...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        // 调用API生成PDF
        const response = await generateTransferPDF({
          orders: transferOrders,
          carrier: this.transferData.carrier
        })

        // 调用API保存PDF到后台
        try {
          await saveTransferPDF({
            orders: transferOrders,
            carrier: this.transferData.carrier
          })
          this.$message.success('PDF已保存到后台')
        } catch (saveError) {
          console.error('保存PDF失败:', saveError)
          this.$message.warning('PDF生成成功，但保存到后台失败')
        }

        // 关闭加载提示
        this.$loading().close()

        if (!response || response.size === 0) {
          throw new Error('生成的PDF为空')
        }

        // 创建Blob对象 - 直接使用response，因为已经是blob
        const blob = new Blob([response], { type: 'application/pdf' })
        const url = URL.createObjectURL(blob)

        // 打开PDF预览对话框
        this.$alert('<iframe src="' + url + '" width="100%" height="500px" frameborder="0"></iframe>', '转运数据PDF预览', {
          dangerouslyUseHTMLString: true,
          customClass: 'pdf-preview-dialog',
          showConfirmButton: true,
          showCancelButton: true,
          confirmButtonText: '打印',
          cancelButtonText: '关闭',
          callback: action => {
            if (action === 'confirm') {
              // 打印PDF
              const printWindow = window.open(url, '_blank')
              if (printWindow) {
                printWindow.onload = function() {
                  printWindow.print()
                }
              }
            }
            // 释放URL对象
            URL.revokeObjectURL(url)
          }
        })

        // 关闭转运数据输入对话框
        this.transferInputVisible = false
      } catch (error) {
        // 关闭加载提示
        this.$loading().close()

        console.error('生成PDF失败:', error)
        let errorMessage = '生成PDF失败，请稍后重试'

        // 尝试从错误响应中获取详细信息
        if (error.response && error.response.data) {
          if (typeof error.response.data === 'string') {
            errorMessage = error.response.data
          } else if (error.response.data.message) {
            errorMessage = error.response.data.message
          } else if (error.response.data.detail) {
            errorMessage = error.response.data.detail
          }
        }

        this.$notify({
          title: '错误',
          message: errorMessage,
          type: 'error',
          duration: 2000
        })
      }
    },
    isEmptyShippingMethod(method) {
      return !method || method === '' || method === null || method === undefined
    },
    async queryPostalCodes() {
      if (!this.list) return
      const searchData = this.list
        .filter(item => this.isEmptyShippingMethod(item.shipping_method) && item.postal_code && item.cw_no)
        .map(item => ({
          postal_code: item.postal_code,
          cw_no: item.cw_no
        }))

      if (searchData.length > 0) {
        try {
          const response = await searchPostalCode(searchData)
          if (response.code === 200 && response.data && response.data.results) {
            response.data.results.forEach(result => {
              // 适配新的邮编查询工具，result.address 现在包含完整的地址信息
              if (result.address) {
                this.$set(this.postalCodeResults, result.postal_code, {
                  address: result.address,
                  city: result.city || '',
                  prefecture: result.prefecture || ''
                })
                // 修复：使用result.cw_no而不是result.fs_no来查找转运单
                const index = this.list.findIndex(item => item.cw_no === result.cw_no)
                if (index !== -1) {
                  // 将查询到的地址信息赋值给 order.state
                  this.$set(this.list[index], 'state', result.address)
                }
              }
            })
            // 等待发货方式查询完成
            await this.queryShippingMethod()
          }
        } catch (error) {
          console.error('查询邮编信息失败:', error)
        }
      }
    },
    async queryShippingMethod() {
      if (!this.list) return

      const itemsNeedShippingMethod = this.list
        .filter(item => this.isEmptyShippingMethod(item.shipping_method) && item.cw_no)

      if (itemsNeedShippingMethod.length > 0) {
        const cwNos = itemsNeedShippingMethod.map(item => item.cw_no)
        try {
          const response = await getShippingMethod({
            cw_no: cwNos
          })
          if (response.code === 200 && response.data && response.data.results) {
            response.data.results.forEach(result => {
              const index = this.list.findIndex(item => item.cw_no === result.cw_no)
              if (index !== -1 && result.shipping_method) {
                this.$set(this.list[index], 'shipping_method', result.shipping_method)
                this.$set(this.list[index], 'sagawa_price', result.sagawa_price)
                this.$set(this.list[index], 'yamato_price', result.yamato_price)
              }
            })
          }
        } catch (error) {
          console.error('批量获取发货方式失败:', error)
        }
      }
    },
    async handleExport() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要导出的数据')
        return
      }
      
      try {
        const ids = this.multipleSelection.map(item => item.id)
        const response = await exportTransferOrders({ ids })
        const blob = new Blob([response], { type: 'application/vnd.ms-excel' })
        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        link.download = `转运订单导出_${new Date().getTime()}.xlsx`
        link.click()
        window.URL.revokeObjectURL(link.href)
        this.$notify({
          title: '成功',
          message: '导出成功',
          type: 'success',
          duration: 2000
        })
      } catch (error) {
        console.error('导出失败:', error)
        this.$notify({
          title: '错误',
          message: error.message || '导出失败',
          type: 'error',
          duration: 2000
        })
      }
    },
    handlePaginationChange({ page, limit }) {
      this.listQuery.page = page
      this.listQuery.page_size = limit  
      this.getList()
    },
    calculateVolume(row) {
      if (row.length && row.width && row.height) {
        const volume = parseFloat(row.length) + parseFloat(row.width) + parseFloat(row.height)
        return volume.toFixed(1)
      }
      return null
    },
    handleBatchUpdateDate() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要修改日期的订单')
        return
      }
      
      // 重置表单
      this.batchDateForm.createTime = ''
      this.batchDateDialogVisible = true
      this.$nextTick(() => {
        this.$refs.batchDateForm.clearValidate()
      })
    },
    async confirmBatchUpdateDate() {
      try {
        const valid = await this.$refs.batchDateForm.validate()
        if (!valid) {
          return
        }
        
        this.batchDateLoading = true
        const cwNos = this.multipleSelection.map(item => item.cw_no)
        await batchUpdateTransferOrdersDate(cwNos, this.batchDateForm.createTime)
        
        this.$notify({
          title: '成功',
          message: `成功修改 ${cwNos.length} 条记录的创建日期`,
          type: 'success',
          duration: 3000
        })
        
        this.batchDateDialogVisible = false
        this.getList() // 刷新列表
      } catch (error) {
        console.error('批量修改日期失败:', error)
        this.$notify({
          title: '错误',
          message: error.message || '批量修改日期失败',
          type: 'error',
          duration: 3000
        })
      } finally {
        this.batchDateLoading = false
      }
    },
    handleViewSavedPDFs() {
      this.savedPDFsVisible = true
      this.loadSavedPDFs()
    },
    handleFilterTypeChange() {
      // 切换筛选方式时清空日期范围
      if (this.pdfFilterForm.filterType === 'days') {
        this.pdfFilterForm.dateRange = []
      } else if (this.pdfFilterForm.filterType === 'dateRange') {
        this.pdfFilterForm.days = 7
      }
      // 重新加载数据
      this.loadSavedPDFs()
    },
    async loadSavedPDFs() {
      this.pdfsLoading = true
      try {
        let params = {}
        
        if (this.pdfFilterForm.filterType === 'days') {
          params.days = this.pdfFilterForm.days
        } else if (this.pdfFilterForm.filterType === 'dateRange' && this.pdfFilterForm.dateRange && this.pdfFilterForm.dateRange.length === 2) {
          params.start_date = this.pdfFilterForm.dateRange[0]
          params.end_date = this.pdfFilterForm.dateRange[1]
        }
        
        const response = await getSavedPDFs(params)
        if (response.code === 200 && response.data) {
          this.savedPDFs = response.data
        } else {
          this.savedPDFs = []
        }
      } catch (error) {
        console.error('获取PDF列表失败:', error)
        this.$message.error('获取PDF列表失败')
        this.savedPDFs = []
      } finally {
        this.pdfsLoading = false
      }
    },
    previewPDF(pdf) {
      this.currentPreviewPDF = pdf
      this.iframeError = false // 重置错误状态
      this.pdfPreviewVisible = true
    },
    onIframeLoad() {
      // iframe加载成功
      this.iframeError = false
    },
    onIframeError() {
      // iframe加载失败
      this.iframeError = true
    },
    getPDFPreviewUrl(pdf) {
      // 构建完整的PDF预览URL
      if (!pdf || !pdf.file_url) return ''
      
      // 如果file_url已经是完整URL，直接返回
      if (pdf.file_url.startsWith('http')) {
        return pdf.file_url
      }
      // 根据当前环境动态构建URL
      // 在开发环境使用localhost:8000，在生产环境使用当前域名
      const isDevelopment = process.env.NODE_ENV === 'development'
      if (isDevelopment) {
        return `http://localhost:8000${pdf.file_url}`
      } else {
        // 生产环境：使用当前域名，nginx会代理到Django服务器
        return `${window.location.origin}${pdf.file_url}`
      }
    },
    openPDFInNewTab() {
      if (this.currentPreviewPDF) {
        const url = this.getPDFPreviewUrl(this.currentPreviewPDF)
        window.open(url, '_blank')
      }
    },
    downloadPDF(pdf) {
      // 使用fetch下载文件，避免跨域问题
      fetch(pdf.file_url, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${this.$store.getters.token}`
        }
      })
      .then(response => {
        if (!response.ok) {
          throw new Error('下载失败')
        }
        return response.blob()
      })
      .then(blob => {
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = pdf.filename
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        this.$message.success('文件下载成功')
      })
      .catch(error => {
        console.error('下载失败:', error)
        this.$message.error('文件下载失败，请检查文件是否存在')
      })
    },
    downloadCurrentPDF() {
      if (this.currentPreviewPDF) {
        this.downloadPDF(this.currentPreviewPDF)
      }
    },
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
    },
    handlePDFSelectionChange(selection) {
      this.selectedPDFs = selection
    },
    async deletePDF(pdf) {
      try {
        await this.$confirm(`确定要删除文件 "${pdf.filename}" 吗？`, '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await deletePDF({ file_path: pdf.file_path })
        this.$message.success('文件删除成功')
        this.loadSavedPDFs() // 重新加载列表
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除文件失败:', error)
          this.$message.error('删除文件失败')
        }
      }
    },
    async batchDeleteSelectedPDFs() {
      if (this.selectedPDFs.length === 0) {
        this.$message.warning('请选择要删除的文件')
        return
      }
      
      try {
        await this.$confirm(`确定要删除选中的 ${this.selectedPDFs.length} 个文件吗？`, '确认批量删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const file_paths = this.selectedPDFs.map(pdf => pdf.file_path)
        const response = await batchDeletePDFs({ file_paths })
        
        if (response.code === 200) {
          this.$message.success(response.message)
          this.loadSavedPDFs() // 重新加载列表
          this.selectedPDFs = [] // 清空选择
        } else {
          this.$message.error(response.message || '批量删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error)
          this.$message.error('批量删除失败')
        }
      }
    },
    async batchDownloadSelectedPDFs() {
      if (this.selectedPDFs.length === 0) {
        this.$message.warning('请选择要下载的文件')
        return
      }
      
      try {
        const file_paths = this.selectedPDFs.map(pdf => pdf.file_path)
        const response = await batchDownloadPDFs({ file_paths })
        
        // 创建下载链接
        const blob = new Blob([response], { type: 'application/zip' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `pdf_files_${new Date().getTime()}.zip`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        
        this.$message.success(`成功下载 ${this.selectedPDFs.length} 个文件`)
      } catch (error) {
        console.error('批量下载失败:', error)
        this.$message.error('批量下载失败')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/dialog-common.scss';
@import '@/styles/shipping-common.scss';

.upload-button {
  display: inline-block;
  margin-right: 10px;
}

/* 体积信息样式 */
.volume-info {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin: 10px 0;
  font-size: 14px;
  color: #606266;
}

/* 上传结果对话框样式 */
::v-deep .upload-result-dialog {
  .el-message-box__message {
    white-space: pre-line;
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    font-size: 13px;
    line-height: 1.6;
    max-height: 400px;
    overflow-y: auto;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 6px;
    border: 1px solid #e9ecef;
    color: #495057;
  }
  
  .el-message-box__title {
    font-weight: 600;
    color: #343a40;
  }
  
  .el-message-box__content {
    padding-bottom: 20px;
  }
}
</style>
